package com.ctgu.chatapp.viewModel

import android.app.Application
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.core.content.res.ResourcesCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import androidx.navigation.Navigation
import androidx.navigation.findNavController
import com.ctgu.chatapp.Netty.NettyClient
import com.ctgu.chatapp.R
import com.ctgu.chatapp.Service.RequestService
import com.ctgu.chatapp.model.Retrofit.IMSServiceImpl
import com.ctgu.chatapp.model.pojo.Information
import com.ctgu.chatapp.utils.Utils
import com.ctgu.chatapp.view.HomePage
import com.ctgu.chatapp.view.IMSApplication
import com.ctgu.chatapp.view.Start
import com.ctgu.chatapp.view.adapter.CoilImageLoader
import com.google.android.material.snackbar.Snackbar
import com.mx.imgpicker.ImagePickerService
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class StartViewModel(application: Application) : AndroidViewModel(application) {

    init {
        ImagePickerService.registerImageLoader(CoilImageLoader())
    }

    val chatID = MutableLiveData("")
    val password = MutableLiveData("")
    val nickname = MutableLiveData("")
    val motto = MutableLiveData("")
    val context by lazy { application }
    val clickShow = MutableLiveData<Boolean>()
    val phone = MutableLiveData("")
    val vC = MutableLiveData("")
    val phoneRegex =
        "^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$"
    val passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$"
    val nicknameRegex = "^[a-zA-Z0-9_-]{4,16}$"
    lateinit var result: String
    val service = IMSServiceImpl.imsServiceImpl.service

    fun signUp(view: View) {
        if (nickname.value.isNullOrEmpty()) {
            viewModelScope.launch(IO) {
                val boolean = service.addUserInfo(
                    Information(
                        result.toLong(),
                        nickname.value!!,
                        0,
                        2,
                        "这个人很懒,还什么也没写",
                        "default",
                        System.currentTimeMillis()
                    )
                )
                withContext(Main) {
                    if (boolean) {
                        val intent = Intent()
                        intent.setClass(context, Start::class.java)
                        context.startActivity(intent)
                    } else {
                        Snackbar.make(view, "提交失败,请重新提交", Snackbar.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    fun skipToNextStep(view: View) {
        if (phone.value.isNullOrEmpty())
            Snackbar.make(view, "请补充完信息再前往下一步", Snackbar.LENGTH_SHORT).show()
        else
            viewModelScope.launch(IO) {
                result = service.checkPhone(
                    phone.value!!,
                    vC.value!!.toInt()
                )
                withContext(Main) {
                    when (result) {
                        "验证码已过期,请重新发送" -> Snackbar.make(view, result, Snackbar.LENGTH_SHORT).show()
                        "验证码错误" -> Snackbar.make(view, "验证码错误", Snackbar.LENGTH_SHORT).show()
                        "手机号已被注册" -> Snackbar.make(view, result, Snackbar.LENGTH_SHORT).show()
                        else -> {
                            password.postValue("")
                            Navigation.findNavController(view)
                                .navigate(R.id.action_Step1_to_Step2)
                        }
                    }
                }
            }
    }

    fun skipToSignUp(view: View) =
        view.findNavController().navigate(R.id.action_login_to_Step1)

    fun skipToForget(view: View) =
        view.findNavController().navigate(R.id.action_login_to_forgetPassword)

    fun login(view: View) {
        if (chatID.value.isNullOrEmpty() || password.value.isNullOrEmpty()) {
            Snackbar.make(view, "请补充完整信息", Snackbar.LENGTH_SHORT)
                .setBackgroundTint(
                    ResourcesCompat.getColor(
                        view.resources,
                        R.color.error,
                        null
                    )
                )
                .setTextColor(ResourcesCompat.getColor(view.resources, R.color.white, null))
                .show()
        } else {
            viewModelScope.launch(Main) {
                withContext(IO) {
                    NettyClient.instance.connect()
                    RequestService.sendLoginRequest(chatID.value!!.toLong(), password.value!!)
                }
            }
        }
    }

    fun showPassword(view: View) {
        if (clickShow.value == false) {
            view.background =
                ResourcesCompat.getDrawable(view.resources, R.drawable.password_invisible, null)
            clickShow.postValue(true)
        } else {
            view.background =
                ResourcesCompat.getDrawable(view.resources, R.drawable.password_visible, null)
            clickShow.postValue(false)
        }
    }

    fun getVC(view: View) {
        if (phone.value!!.isNotEmpty()) {
            var int = 60
            val handler = Handler(Looper.myLooper()!!)
            handler.post(object : Runnable {
                override fun run() {
                    (view as Button).text = int.toString()
                    if (int == 60) view.isClickable = false
                    int--
                    if (int == 0) {
                        view.isClickable = true
                        view.text = "获取验证码"
                        return
                    }
                    handler.postDelayed(this, 1000)
                }
            })
            viewModelScope.launch {
                val v = service.getVerificationCode(phone.value!!)
                Snackbar.make(view, v.toString(), 60000).show()
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        chatID.value = ""
        password.value = ""
        viewModelScope.cancel()
    }

    companion object {
        val handler = object : Handler(Looper.myLooper()!!) {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                val result = msg.obj as com.ctgu.chatapp.Netty.protocol.Message.IMSMsg
                Toast.makeText(
                    IMSApplication.context,
                    result.loginResponse.reason,
                    Toast.LENGTH_LONG
                ).show()
                if (result.loginResponse.resultType) {
                    Utils.chatID = result.head.fromId
                    MainViewModel.chatID = result.head.fromId
                    val intent = Intent(IMSApplication.context, HomePage::class.java)
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    IMSApplication.context.startActivity(intent)
                }
            }
        }
    }
}